package com.kapo.egroup.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kapo.egroup.common.ResponseEnum;
import com.kapo.egroup.common.Result;
import com.kapo.egroup.entity.base.project.UserApplyRecord;
import com.kapo.egroup.entity.base.user.User;
import com.kapo.egroup.security.domain.LoginUser;
import com.kapo.egroup.service.UserService;
import com.kapo.egroup.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Title UserController
 * @Description TODO
 * @Author 86159
 * @Date 2022-10-11 19:46
 **/
@RestController
@RestControllerAdvice
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    PasswordEncoder passwordEncoder;

//    @PostMapping("/login")
//    Result login(@RequestBody LoginReq loginReq){
//
//        return Result.ok(userService.login(loginReq));
//    }
    @ResponseBody
    @PostMapping("/register")
    Result register(User userRequest){
        if(StringUtils.isEmpty(userRequest.getEmail()) && StringUtils.isEmpty(userRequest.getPhone())){
            return Result.fail().result(ResponseEnum.EXCEPTION);
        }
        User user = null;
        if(userRequest.getEmail() != null){
            user = userService.selectByEmail(userRequest.getEmail());
        }else if(userRequest.getPhone() != null){
            user = userService.selectByPhone(userRequest.getPhone());
        }
        //用户名重复
        if(!ObjectUtil.isEmpty(user)){
            return Result.fail().result(ResponseEnum.DUPLICATE_USERNAME);
        }
        //密码需经加密储存
        userRequest.setPassword(passwordEncoder.encode(userRequest.getPassword()));

        userService.save(userRequest);

        return Result.ok();
    }

    @GetMapping("/logout")
    Result logout(HttpServletRequest request, HttpServletResponse response){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return Result.ok();
    }

    @GetMapping("")
    Result getUserInfo(@RequestParam(required = false) Long userId){
        if(userId==null){
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userService.selectByUsername(username);
            return Result.ok(user);
        }else{
            User user = userService.getById(userId);
            return Result.ok(user);
        }
    }

    @GetMapping("/checkusername/{username}")
    Result checkUsername(@PathVariable String username){
        User user = null;
        user = userService.selectByPhone(username);
        //用户名重复
        if(!ObjectUtil.isEmpty(user)){
            return Result.fail().result(ResponseEnum.DUPLICATE_USERNAME);
        }
        return Result.ok(user);
    }

    //  修改用户基础信息（不含密码、邮箱、手机号）
    @CrossOrigin
    @ResponseBody
    @PutMapping("")
    public Result updateUser(User userUpdated){
        User user = new User();
        //  不能修改手机号、邮箱、密码
        user.setAvatar(userUpdated.getAvatar());
        user.setMajorId(userUpdated.getMajorId());
        user.setNickname(userUpdated.getNickname());
        user.setGender(userUpdated.getGender());
        user.setWechatNumber(userUpdated.getWechatNumber());
        user.setSchoolId(userUpdated.getSchoolId());
        user.setId(getCurrentUserId());
        userService.updateById(user);
        return Result.ok(user);
    }

    private Long getCurrentUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object user = authentication.getPrincipal();
        LoginUser loginUser = (LoginUser)user;
        return loginUser.getUserId();
    }
}
